package com.xu.t1.controller;

import com.xu.t1.common.RecordGenerator;
import com.xu.t1.enums.DispatchResult;
import com.xu.t1.mapper.LearningRecordMapper;
import com.xu.t1.middleware.online.OnlineUserManager;
import com.xu.t1.model.LearningRecord;
import com.xu.t1.model.PageResult;
import com.xu.t1.model.UploadLog;
import com.xu.t1.service.LearningRecordDispatcher;
import com.xu.t1.service.LearningRecordService;
import com.xu.t1.service.UploadLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;


/**
 * 负责学习记录的查询和写入的控制层接口类
 *
 * @author xu
 *
 */

@RestController
@RequestMapping("/api/records")
public class LearningRecordController {

    @Value("${app.server-id}")
    private String serverId;


    @Autowired
    private LearningRecordMapper learningRecordMapper;

    @Autowired
    private LearningRecordDispatcher dispatcher;

    @Autowired
    private LearningRecordService recordService;

    @Autowired
    private UploadLogService uploadLogService;

    @Autowired
    private OnlineUserManager onlineUserManager;


    //根据用户ID查询该用户的所有学习记录
    @GetMapping("/user/{userId}")
    public List<LearningRecord> getRecordsByUserId(@PathVariable Long userId) {
        return learningRecordMapper.findRecordsByUserId(userId);
    }

    //分页查询用户的学习记录
    @GetMapping("/user/page/{userId}")
    public PageResult<LearningRecord> getRecordsByUserIdPage(@PathVariable Long userId,
                                                             @RequestParam(defaultValue = "1") int page,
                                                             @RequestParam(defaultValue = "20") int size){
        return recordService.getRecordsByUserIdPagedWithCache(userId, page, size);
    }

    //真实写入
//    @PostMapping("/dispatch")
//    public String dispatch(
//            @RequestBody List<LearningRecord> records,
//            @RequestParam int totalSize,
//            @RequestParam String instructionId,         // 操作指令ID
//            @RequestHeader("X-Client-Id") String clientId // 客户端标识
//    ) {
//
//        // 记录日志
//        UploadLog log = new UploadLog();
//        log.setServerId(serverId);
//        log.setLogId(UUID.randomUUID().toString());
//        log.setInstructionId(instructionId);
//        log.setUserId(clientId);  //客户端ID
//        log.setTimestamp(System.currentTimeMillis());
//
//
//        boolean success = dispatcher.dispatch(records, totalSize,log);
//
//        log.setDurationMs(System.currentTimeMillis() - log.getTimestamp());
//
//        //保存日志到sql
//        uploadLogService.insertUploadLog(log);
//
//
//        return success ? "Dispatch successful" : "Dispatch failed";
//    }


    @PostMapping("/dispatch/start")
    public String dispatchStart(
            @RequestParam int totalSize,
            @RequestParam String instructionId,
            @RequestHeader("X-Client-Id") String clientId
    ) {
        // 在服务端本地生成模拟学习记录数据
        List<LearningRecord> records = RecordGenerator.generateFixedRecords(totalSize);

        // 构造日志对象
        UploadLog log = new UploadLog();
        log.setServerId(serverId);
        log.setLogId(UUID.randomUUID().toString());
        log.setInstructionId(instructionId);
        log.setUserId(clientId);
        log.setTimestamp(System.currentTimeMillis());

        onlineUserManager.refreshUserOnline(clientId,serverId);

        // 调用内部调度逻辑
        DispatchResult success = dispatcher.dispatch(records, totalSize, log);

        log.setDurationMs(System.currentTimeMillis() - log.getTimestamp());
        uploadLogService.insertUploadLog(log);

        return switch (success) {
            case SUCCESS -> "写入成功";
            case FAILED -> "写入失败，系统回滚";
            case BUSY -> "系统繁忙或未获得写入权限"; //可做成自旋尝试
        };
    }

}